<template>
  <div style="width: 100%; height: 400px">
    <el-empty v-if="emptyVisible" :description="$t('common.empty_tip')" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/mixins/resize'
import { getAppVersionPie } from '@/api/app'
import { get } from 'js-cookie'

export default {
  mixins: [resize],
  props: {
    chartMode: Object
  },
  data() {
    return {
      data: [],
      props: {
        chartMode: Object
      },
      chart: null,
      emptyVisible: false
    }
  },
  mounted() {
    this.initData()
  },

  methods: {
    initData() {
      getAppVersionPie({ appPackageName: this.$route.query.packageName })
        .then((res) => {
          const formatData = []
          res.forEach((version) => {
            const _version = {}
            _version.name = version.versionName
            _version.value = version.installedDeviceCount
            formatData.push(_version)
          })
          this.data = this.dataFilter(formatData, 10)

          if (this.data != null && this.data.length > 0) {
            this.initChart()
          } else {
            this.emptyVisible = true
          }
        })
        .catch((err) => {
          this.$confirmError(err)
        })
    },
    /**
     * 排序数组，显示前 k-1 个数据，多余的数据合并成 other，
     * @param {Array} arr 需要排序的数组
     * @param {Num} k 显示 k 个结果
     */
    dataFilter(arr, k = 6) {
      let _data = []
      if (!arr) {
        return _data
      }
      if (arr && arr.length <= k) {
        return arr
      }
      _data = [...arr].sort((a, b) => (a.value < b.value) ? 1 : -1)
      let bigArr = _data.splice(0, k-1)
        let sum = 0
        _data.forEach((item) => {
          sum += item.value
        })
        bigArr.push({ name: 'Other', value: sum })
      return bigArr
    },
    initChart() {
      this.chart = echarts.init(this.$el)
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['30%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'center',
              normal: {
                formatter: '{b}:{c}: ({d}%)',
                textStyle: {
                  fontWeight: 'normal',
                  fontSize: 15
                }
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            data: this.data
          }
        ]
      }
      this.chart.setOption(option, true)
    }
  }
}
</script>

<style></style>
